//
//  ContainerView.m
//  Test
//
//  Created by jingyao on 2017/12/12.
//  Copyright © 2017年 jingyao. All rights reserved.
//

#import "ContainerView.h"
#import "DraggableCardView.h"

@interface ContainerView()<UIGestureRecognizerDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray<CardData *> *cardDataArray;//原来顺序的数据
@property (nonatomic, strong) NSMutableArray<CardData *> *internerCardDataArray;//内部排序使用

@property (assign, nonatomic) CGPoint beginInViewPoint;
@property (assign, nonatomic) CGPoint cardCenterPoint;
@property (assign, nonatomic) CGPoint velocityDirection;
@property (assign, nonatomic) Boolean isHorizontallyMoving;

@end


@implementation ContainerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    [self reloadCardDatas];
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    
    [self reloadCardDatas];
    return self;
}

- (void)resetCardDatas {
    
    self.internerCardDataArray = [self.cardDataArray mutableCopy];
    [self reloadCardDatas];
}

- (void)reloadCardDatas {
    //移除已有的cardview
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[DraggableCardView class]]) {
            [view removeFromSuperview];
        }
    }
    
    //根据数组中的数据创建新的cardView并添加到界面上
    //只显示三张
    NSInteger lastIndex = self.internerCardDataArray.count > 3 ? 2 : self.internerCardDataArray.count - 1;
    for (NSInteger index = lastIndex; index >= 0; index--) {
        
        [self createCardViewWithShowSequence:index AndCardData:self.internerCardDataArray[index]];
        
    }
}

//初始化cardViews
- (void)generateCardViewsWithCardArray:(NSMutableArray<CardData *> *) cardDataArray {
    
    self.cardDataArray = cardDataArray;
    self.internerCardDataArray = [cardDataArray mutableCopy];
    [self reloadCardDatas];
}


- (void)createCardViewWithShowSequence:(NSUInteger)sequence AndCardData:(CardData *)cardData {
    //添加卡牌view
    DraggableCardView *draggableCardView = [DraggableCardView createFromXibWithName:cardData.xibName];
    draggableCardView.sequence = sequence;//用于拖的时候判断谁是第一个
    [self addSubview:draggableCardView];

    draggableCardView.layer.cornerRadius = 10.0f;
    draggableCardView.layer.shadowOpacity = 0.5;// 阴影透明度
    draggableCardView.layer.shadowColor = [UIColor grayColor].CGColor;// 阴影的颜色
    draggableCardView.layer.shadowRadius = 3;// 阴影扩散的范围控制
    draggableCardView.layer.shadowOffset = CGSizeMake(1, 1);// 阴影的范围
    
   // draggableCardView.layer.masksToBounds = YES;
   // draggableCardView.layer.borderWidth = 1.0f;
    //draggableCardView.layer.borderColor = [UIColor redColor].CGColor;
    [draggableCardView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    //位置
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:draggableCardView attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:draggableCardView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant: -18.0f * sequence]];
    
    //宽，高
    [self addConstraint:[NSLayoutConstraint constraintWithItem:draggableCardView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:0.8f constant:sequence * -18.0f]];
    
    CGFloat deltaHeight = 0;
    if (sequence == 0) {
        deltaHeight = -18.0f * sequence;
    } else if (sequence == 1) {
        deltaHeight = -18.0f * sequence;
    } else if (sequence == 2) {
        deltaHeight = -18.0f * sequence  - 10.0f;
    } else {
        deltaHeight = -18.0f * (sequence + 1);
    }
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:draggableCardView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeHeight multiplier:.9f constant:deltaHeight]];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureHandle:)];
    pan.delegate = self;
    [draggableCardView addGestureRecognizer:pan];
}

//拖拽手势事件方法
- (void)panGestureHandle:(UIPanGestureRecognizer *)gesture {
    DraggableCardView *cardView = (DraggableCardView *)gesture.view;
    
    //如果拖住的不是第一张卡，就不作处理
    if (cardView.sequence != 0) {
        return;
    }
    
    switch (gesture.state) {
        case UIGestureRecognizerStatePossible:
        break;
            
        case UIGestureRecognizerStateBegan:
            //初始化赋值
            self.beginInViewPoint = [gesture locationInView:self];
            self.cardCenterPoint = cardView.center;
            self.velocityDirection = [gesture velocityInView:self];//开始滑动时的速率值
            
            //记录一上来手指移动的方向
            if (fabs(self.velocityDirection.x) > fabs(self.velocityDirection.y)) {
                self.isHorizontallyMoving = YES;

            }else {
                self.isHorizontallyMoving = NO;
                
            }
            
            if ([self.superview isKindOfClass:[UIScrollView class]]) {
                UIScrollView *scrollView = (UIScrollView *)self.superview;
                scrollView.scrollEnabled = self.isHorizontallyMoving;
            }
            
        break;
            
        case UIGestureRecognizerStateChanged:{
            //case后面不能直接定义新的东西，要加花括号。临时变量，记录手指当前位置
            CGPoint currentFingerPoint = [gesture locationInView:self];
            
            //记录手指移动的距离
            CGFloat deltaX = currentFingerPoint.x - self.beginInViewPoint.x;
            CGFloat deltaY = currentFingerPoint.y - self.beginInViewPoint.y;
            
            
            //如果是横向移动的开始，不作处理
            if (self.isHorizontallyMoving) {

            }else {
                //view需要将中心点移动到
                CGPoint showCardViewCenterPoint = CGPointMake(self.cardCenterPoint.x + deltaX, self.cardCenterPoint.y + deltaY);
                cardView.center = showCardViewCenterPoint;
                
                //显示有倾斜角度的动画
                [self showRotationWithView:cardView AndTouchPoint:currentFingerPoint AndDeltaX:deltaX];
                
                //让底部的控件变大一点
                [self showScaleOtherCardViewsWithDeltaX:deltaX AndDeltaY:deltaY];
            }
        }
        break;
            
        case UIGestureRecognizerStateEnded: {
            CGPoint velocityEndDirection = [gesture velocityInView:self];//松手时候的速率
            if (self.isHorizontallyMoving) {


                
            }else {
                if (fabs(velocityEndDirection.y) > fabs(self.velocityDirection.y)) {
                    //如果松手的速度比开始滑动时快，那么就要把view移除掉
                    [self showRemoveView:cardView WithVelocity:velocityEndDirection];
                    [self showOtherCardViewsNewAnimation];

                }else {
                    //否则松手弹回原处，做出动画效果
                    [self showBoundingView:cardView To:self.cardCenterPoint];
                    
                    [self showOtherCardViewsOriginAnimation];
                }
            }
            
            self.isHorizontallyMoving = NO;
            
            if ([self.superview isKindOfClass:[UIScrollView class]]) {
                UIScrollView *scrollView = (UIScrollView *)self.superview;
                scrollView.scrollEnabled = YES;
            }

        }
        break;
            
        case UIGestureRecognizerStateCancelled:
        break;
            
        case UIGestureRecognizerStateFailed:
        break;
            
        default:
        break;
    }
}

- (void)showOtherCardViewsOriginAnimation {
    [UIView animateWithDuration:0.5 animations:^{
        for (UIView *view in self.subviews) {
            if ([view isKindOfClass:[DraggableCardView class]]) {
                DraggableCardView *cardView = (DraggableCardView *)view;
                if (cardView.sequence > 0) {
                    //放大
                    //cardView.transform = CGAffineTransformMakeScale(1 + (deltaRate * 0.1), 1 + (deltaRate * 0.1));
                    //还原动画的方法
                    cardView.transform = CGAffineTransformIdentity;
                }
            }
        }
    }];
}

- (void)showOtherCardViewsNewAnimation {
    [UIView animateWithDuration:0.5 animations:^{
        for (UIView *view in self.subviews) {
            if ([view isKindOfClass:[DraggableCardView class]]) {
                DraggableCardView *cardView = (DraggableCardView *)view;
                if (cardView.sequence > 0) {
                    //把控件的位置更新为下一次出现的位置
                    CGFloat destinationWidth = self.frame.size.width * 0.8 - (cardView.sequence - 1) * (18);
                    CGFloat currentWidth = self.frame.size.width * 0.8 - cardView.sequence * (18);
                    //放大了倍数
                    CGFloat scaleRate = (destinationWidth-currentWidth)/currentWidth;
                    
                    cardView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -18);
                    cardView.transform = CGAffineTransformScale(cardView.transform, 1 + scaleRate, 1 + scaleRate);
                }
            }
        }
    }];
}

- (void)showRotationWithView:(UIView *)rotateView AndTouchPoint:(CGPoint)touchPoint AndDeltaX:(CGFloat)deltaX {
    CGFloat angle = deltaX/self.frame.size.height * 0.5f * M_PI_4;
    rotateView.transform = CGAffineTransformMakeRotation(angle);
}

//放大底下的cardviews
- (void)showScaleOtherCardViewsWithDeltaX:(CGFloat) deltaX AndDeltaY:(CGFloat) deltaY {
    //计算手指移动的斜方向的距离,与屏幕距离的比例
    CGFloat deltaDistance = sqrt(deltaX * deltaX + deltaY * deltaY);
    CGFloat deltaRate = deltaDistance / sqrt(self.frame.size.width * self.frame.size.width + self.frame.size.height * self.frame.size.height);
    
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[DraggableCardView class]]) {
            DraggableCardView *cardView = (DraggableCardView *)view;
            if (cardView.sequence > 0) {
                
                CGFloat destinationWidth = self.frame.size.width * 0.8;
                CGFloat destinationHeight = self.frame.size.height * 0.8;
                CGFloat currentWidth = self.frame.size.width * 0.8 - cardView.sequence * (18);
                //放大了倍数
                CGFloat scaleRate = (destinationWidth-currentWidth)/currentWidth;
                
                
                cardView.transform = CGAffineTransformMakeScale(1 + (scaleRate * deltaRate), 1 + (deltaRate * scaleRate));
                cardView.transform = CGAffineTransformTranslate(cardView.transform, 0, -(scaleRate * deltaRate) * destinationHeight);
                //还原动画的方法CGAffineTransformIdentity
            }
        }
    }
}

- (void)showBoundingView:(UIView *) view To:(CGPoint) toPoint {
    CGPoint fromPoint = view.center;
    
    //计算途经点
    CGFloat deltaX = (toPoint.x - fromPoint.x);
    CGFloat deltaY = (toPoint.y - fromPoint.y);
    CGFloat length = sqrtf(powf(deltaX, 2) + powf(deltaY, 2));
    
    if (length == 0) {
        return;
    }
    
    //途经点1
    CGFloat passByPoint1X = toPoint.x + deltaX/length * 8;
    CGFloat passByPoint1Y = toPoint.y + deltaY/length * 8;
    CGPoint passByPoint1 = CGPointMake(passByPoint1X, passByPoint1Y);
    
    //途经点2
    CGFloat passByPoint2X = toPoint.x - deltaX/length * 3;
    CGFloat passByPoint2Y = toPoint.y - deltaY/length * 3;
    CGPoint passByPoint2 = CGPointMake(passByPoint2X, passByPoint2Y);
    
    
    
    [UIView animateWithDuration:0.4 animations:^{
        view.center = passByPoint1;
        view.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            view.center = passByPoint2;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                view.center = toPoint;
            } completion:^(BOOL finished) {
                
            }];
        }];
    }];
}

- (void)showRemoveView:(UIView *) view WithVelocity:(CGPoint) velocity {
    CGFloat distance = sqrtf(powf(self.frame.size.width, 2) + powf(self.frame.size.height, 2));
    
    CGFloat length = sqrtf(powf(velocity.x, 2) + powf(velocity.y, 2));
    
    CGFloat deltaX = velocity.x / length * distance;
    CGFloat deltaY = velocity.y / length * distance;
    CGPoint removePoint = CGPointMake(view.center.x + deltaX, view.center.y + deltaY);
    
    [UIView animateWithDuration:0.5 animations:^{
        view.center = removePoint;
    } completion:^(BOOL finished) {
        CardData *cardData = self.internerCardDataArray[0];
        [self.internerCardDataArray removeObjectAtIndex:0];
        [self.internerCardDataArray addObject:cardData];
        
        [self reloadCardDatas];
    }];
}


#pragma mark UIGestureDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    if (self.isHorizontallyMoving) {
        return NO;
    }
    
    return YES;
}

/*
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return NO;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0) {
    return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer NS_AVAILABLE_IOS(7_0) {
    return YES;
}

// called before touchesBegan:withEvent: is called on the gesture recognizer for a new touch. return NO to prevent the gesture recognizer from seeing this touch
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

// called before pressesBegan:withEvent: is called on the gesture recognizer for a new press. return NO to prevent the gesture recognizer from seeing this press
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceivePress:(UIPress *)press {
    return YES;
}
 */

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([otherGestureRecognizer.view isKindOfClass:[UIScrollView class]]) {
        return YES;
        
    } else {
        return NO;
    }
}

@end
